package com.gk.panda.apis.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gk.panda.apis.dto.HeartbeatDto;
import com.gk.panda.apis.dto.UmwCameraDto;
import com.gk.panda.apis.dto.UmwWIFIDto;
import com.gk.panda.apis.entity.wifiCapture.WiFiCaptureEntity;
import com.gk.panda.apis.entity.wifiCapture.WifiRequestInfo;
import com.gk.panda.apis.service.*;
import com.gk.panda.apis.util.MultipartFileDto;
import com.gk.panda.commons.controller.BaseController;
import com.gk.panda.commons.exception.ServerException;
import com.gk.panda.commons.page.TableDataInfo;
import com.gk.panda.commons.result.Result;
import com.gk.panda.pojo.DeviceManager;
import com.gk.panda.pojo.RealtimeShoot;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/umwcamera")
@Api(tags = "umw5Pwifi相机")
public class UmwWiFiController extends BaseController{

    @Autowired
    private FdfsService fdfsService;

    @Autowired
    private WiFiCaptureService wiFiCaptureService;

    @Autowired
    private DeviceManagerService deviceManagerService;

    @Autowired
    private RealtimeShootService realtimeShootService;

    @Autowired
    private EventTodoService eventTodoService;

    @ApiOperation(value = "存储照片缩略图")
    @PostMapping("/addPhotos")
    public Result<String> addPhoto(HttpServletRequest request) throws Exception {
        if(ObjectUtils.isEmpty(request)){
            return Result.write(201,"存储照片缩略图失败");
        }
        WifiRequestInfo info = new WifiRequestInfo();
        info.setCameraCode(request.getParameter("cameraCode"));
        wiFiCaptureService.insertWifiRequestInfo(info);
        //获取值
        UmwCameraDto dto = new UmwCameraDto();
        dto.setCameraCode(request.getParameter("cameraCode"));
        dto.setDate(request.getParameter("date"));
        dto.setTime(request.getParameter("time"));
        dto.setVideoLength(request.getParameter("videoLength"));
        dto.setVideoSize(request.getParameter("videoSize"));
        dto.setLatitude(request.getParameter("latitude"));
        dto.setLongitude(request.getParameter("longitude"));
        dto.setTemperature(request.getParameter("temperature"));
        dto.setColorMode(request.getParameter("colorMode"));
        dto.setUploadRate(request.getParameter("uploadRate"));
        dto.setSignal(request.getParameter("signal"));
        dto.setCapacity(request.getParameter("capacity"));
        dto.setFreeSpace(request.getParameter("freeSpace"));
        dto.setFirmware(request.getParameter("firmware"));
        dto.setFileID(request.getParameter("fileID"));
        dto.setBattery(request.getParameter("battery"));

        //解析文件流
        MultipartFile multipartFile = ((MultipartHttpServletRequest) request).getFile("file");
        dto.setFile(multipartFile);


//        //获取文件名
        String[] fileNameAttr = dto.getFile().getOriginalFilename().split("\\.");
        //获取文件的后缀
        String suffix = fileNameAttr[fileNameAttr.length - 1];
        //上传，获取文件访问地址
        String url = fdfsService.uploadFile(dto.getFile(),suffix);

        System.out.println("*******"+dto.toString());

        //todo 存表
        WiFiCaptureEntity wiFiCaptureEntity = new WiFiCaptureEntity();
        wiFiCaptureEntity.setCameraCode(dto.getCameraCode());
        wiFiCaptureEntity.setPath(url);
        wiFiCaptureEntity.setDates(dto.getDate());
        wiFiCaptureEntity.setTimes(dto.getTime());
        wiFiCaptureEntity.setUploadRate(dto.getUploadRate());
        wiFiCaptureEntity.setFileId(dto.getFileID());
        wiFiCaptureService.insertWiFiCapture(wiFiCaptureEntity);

        DeviceManager device = deviceManagerService.getDeviceBySn(dto.getCameraCode());
        RealtimeShoot realtimeShoot = new RealtimeShoot();
        realtimeShoot.setDeviceName(device.getDeviceName());
        realtimeShoot.setDeviceSn(dto.getCameraCode());
        realtimeShoot.setPath(url);
//        if (StringUtils.isNotBlank(dto.getDate()) && StringUtils.isNotBlank(dto.getTime())) {
//            Date getTime = dateFormat(dto.getDate() + " " + dto.getTime());
//            realtimeShoot.setGetTime(getTime);
//        } else {
//            realtimeShoot.setGetTime(new Date());
//        }
        realtimeShoot.setGetTime(new Date());//使用系统时间
        realtimeShoot.setEvent("自动上传");
        realtimeShoot.setSource(0);
        realtimeShoot.setLot(device.getLongitude());
        realtimeShoot.setLat(device.getLatitude());
        realtimeShoot.setPlace(device.getDeviceAddress());
        realtimeShoot.setOrgId(device.getFkOrgId());
        realtimeShootService.save(realtimeShoot);

        //更新电量
        String battery = dto.getBattery();
        if (StringUtils.isNotBlank(battery)) {
            UpdateWrapper<DeviceManager> wrapper = new UpdateWrapper<>();
            wrapper.eq("device_sn",dto.getCameraCode());
            wrapper.set("remaining_electricity", battery +"0%");
            deviceManagerService.update(wrapper);
            if (Integer.parseInt(battery) <= 3) {
                eventTodoService.saveBatteryEvent(device);
            }
        }
        return Result.write(200,"存储照片缩略图成功");
    }

    @ApiOperation(value = "存储视频缩略图")
    @PostMapping("/addVideo")
    public Result<String> addVideo(HttpServletRequest request) throws Exception {

        WifiRequestInfo info = new WifiRequestInfo();
        info.setCameraCode(request.getParameter("cameraCode"));
        wiFiCaptureService.insertWifiRequestInfo(info);
        //获取值
        UmwCameraDto dto = new UmwCameraDto();
        dto.setCameraCode(request.getParameter("cameraCode"));
        dto.setDate(request.getParameter("date"));
        dto.setTime(request.getParameter("time"));
        dto.setVideoLength(request.getParameter("videoLength"));
        dto.setVideoSize(request.getParameter("videoSize"));
        dto.setLatitude(request.getParameter("latitude"));
        dto.setLongitude(request.getParameter("longitude"));
        dto.setTemperature(request.getParameter("temperature"));
        dto.setPhotoSource(request.getParameter("photoSource"));
        dto.setColorMode(request.getParameter("colorMode"));
        dto.setUploadRate(request.getParameter("uploadRate"));
        dto.setSignal(request.getParameter("signal"));
        dto.setCapacity(request.getParameter("capacity"));
        dto.setFreeSpace(request.getParameter("freeSpace"));
        dto.setTimeStamp(request.getParameter("timeStamp"));
        dto.setFirmware(request.getParameter("firmware"));
        dto.setFileID(request.getParameter("fileID"));
        dto.setBattery(request.getParameter("battery"));

        //解析文件流
        MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("file");
        dto.setFile(multipartFile);

        if(ObjectUtils.isEmpty(dto)){
            return Result.write(201,"存储视频缩略图失败");
        }

        System.out.println("*******"+dto.toString());

        //获取文件名
        String[] fileNameAttr = dto.getFile().getOriginalFilename().split("\\.");
        //获取文件的后缀
        String suffix = fileNameAttr[fileNameAttr.length - 1];
        //上传，获取文件访问地址
        String url = fdfsService.uploadFile(dto.getFile(),suffix);
        //todo 存表
        WiFiCaptureEntity wiFiCaptureEntity = new WiFiCaptureEntity();
        wiFiCaptureEntity.setCameraCode(dto.getCameraCode());
        wiFiCaptureEntity.setPath(url);
        wiFiCaptureEntity.setDates(dto.getDate());
        wiFiCaptureEntity.setTimes(dto.getTime());
        wiFiCaptureEntity.setUploadRate(dto.getUploadRate());
        wiFiCaptureEntity.setFileId(dto.getFileID());
        wiFiCaptureService.insertWiFiCapture(wiFiCaptureEntity);

        DeviceManager device = deviceManagerService.getDeviceBySn(dto.getCameraCode());
        RealtimeShoot realtimeShoot = new RealtimeShoot();
        realtimeShoot.setDeviceName(device.getDeviceName());
        realtimeShoot.setDeviceSn(dto.getCameraCode());
        realtimeShoot.setPath(url);
//        if (StringUtils.isNotBlank(dto.getDate()) && StringUtils.isNotBlank(dto.getTime())) {
//            Date getTime = dateFormat(dto.getDate() + " " + dto.getTime());
//            realtimeShoot.setGetTime(getTime);
//        } else {
//            realtimeShoot.setGetTime(new Date());
//        }
        realtimeShoot.setGetTime(new Date());//使用系统时间
        realtimeShoot.setEvent("自动上传");
        realtimeShoot.setSource(0);
        realtimeShoot.setLot(device.getLongitude());
        realtimeShoot.setLat(device.getLatitude());
        realtimeShoot.setPlace(device.getDeviceAddress());
        realtimeShoot.setOrgId(device.getFkOrgId());
        realtimeShootService.save(realtimeShoot);

        //更新电量
        String battery = dto.getBattery();
        if (StringUtils.isNotBlank(battery)) {
            UpdateWrapper<DeviceManager> wrapper = new UpdateWrapper<>();
            wrapper.eq("device_sn",dto.getCameraCode());
            wrapper.set("remaining_electricity", battery +"0%");
            deviceManagerService.update(wrapper);
            if (Integer.parseInt(battery) <= 3) {
                eventTodoService.saveBatteryEvent(device);
            }
        }
        return Result.write(200,"存储视频缩略图成功");
    }

    @ApiOperation(value = "上传原图或（小）视频")
    @PostMapping("/addOriginalPhoVid")
    public Result<String> uploadTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {

        WifiRequestInfo info = new WifiRequestInfo();
        info.setCameraCode(request.getHeader("x-cameracode"));
        wiFiCaptureService.insertWifiRequestInfo(info);
        //获取请求头中的数据，替换无法识别的符号
        String x_cameracode = request.getHeader("x-cameracode");
        String x_file_id = request.getHeader("x-file-id");
        String x_date = request.getHeader("x-date");
        String x_time = request.getHeader("x-time");
        String x_is_hq = request.getHeader("x-is-hq");
        String x_firmware = request.getHeader("x-firmware");
        String x_video_size = request.getHeader("x-video-size");
        String x_send_video_size = request.getHeader("x-send-video-size");
        String x_latitude = request.getHeader("x-latitude");
        String x_longitude = request.getHeader("x-longitude");
        String x_temperature = request.getHeader("x-temperature");
        String x_photosource = request.getHeader("x-photosource");
        String x_colormode = request.getHeader("x-colormode");
        String x_upload_rate = request.getHeader("x-upload-rate");
        String x_signal = request.getHeader("x-signal");
        String x_battery = request.getHeader("x-battery");
        String x_capacity = request.getHeader("x-capacity");
        String x_freespace = request.getHeader("x-freespace");
        String Content_Type = request.getHeader("Content-Type");

        UmwCameraDto dto = new UmwCameraDto();
        dto.setCameraCode(request.getParameter("x-cameracode"));
        dto.setDate(request.getParameter("x-date"));
        dto.setTime(request.getParameter("x-time"));
        dto.setVideoLength(request.getParameter("x-video-size"));
        dto.setVideoSize(request.getParameter("x-send-video-size"));
        dto.setLatitude(request.getParameter("x-latitude"));
        dto.setLongitude(request.getParameter("x-longitude"));
        System.out.println("*******"+dto.toString());

        MultipartFile file = tranMultipartFile(request.getInputStream(),Content_Type);
        //获取文件上传的名称
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            throw new ServerException("上传文件有误，请确认！");
        }

        String[] fileNameAttr = originalFilename.split("\\.");
        //获取文件的后缀
        String suffix = fileNameAttr[fileNameAttr.length - 1];
        String url = fdfsService.uploadFile(file,suffix);

        request.getInputStream();
        //文件总大小
        response.setHeader("x-file-uploaded-size",file.getSize()+"");
        //续传几次累加上传的文件大小,续传需要累计，暂时不知道如何累计
        response.setHeader("x-file-session-uploaded-size",file.getSize()+"");

        //todo 存表
        WiFiCaptureEntity wiFiCaptureEntity = new WiFiCaptureEntity();
        wiFiCaptureEntity.setCameraCode(x_cameracode);
        wiFiCaptureEntity.setPath(url);
        wiFiCaptureEntity.setDates(x_date);
        wiFiCaptureEntity.setTimes(x_time);
        wiFiCaptureEntity.setUploadRate(x_upload_rate);
        wiFiCaptureEntity.setFileId(x_file_id);
        wiFiCaptureService.insertWiFiCapture(wiFiCaptureEntity);

        DeviceManager device = deviceManagerService.getDeviceBySn(x_cameracode);
        RealtimeShoot realtimeShoot = new RealtimeShoot();
        realtimeShoot.setDeviceName(device.getDeviceName());
        realtimeShoot.setDeviceSn(x_cameracode);
        realtimeShoot.setPath(url);
//        if (StringUtils.isNotBlank(x_date) && StringUtils.isNotBlank(x_time)) {
//            Date getTime = dateFormat(x_date + " " + x_time);
//            realtimeShoot.setGetTime(getTime);
//        } else {
//            realtimeShoot.setGetTime(new Date());
//        }
        realtimeShoot.setGetTime(new Date());//使用系统时间
        realtimeShoot.setEvent("自动上传");
        realtimeShoot.setSource(0);
        realtimeShoot.setLot(device.getLongitude());
        realtimeShoot.setLat(device.getLatitude());
        realtimeShoot.setPlace(device.getDeviceAddress());
        realtimeShoot.setOrgId(device.getFkOrgId());
        realtimeShootService.save(realtimeShoot);
        //更新电量
        if (StringUtils.isNotBlank(x_battery)) {
            UpdateWrapper<DeviceManager> wrapper = new UpdateWrapper<>();
            wrapper.eq("device_sn",dto.getCameraCode());
            wrapper.set("remaining_electricity", x_battery +"0%");
            deviceManagerService.update(wrapper);
            if (Integer.parseInt(x_battery) <= 3) {
                eventTodoService.saveBatteryEvent(device);
            }
        }


        return Result.write(200,"上传原图或（小）视频成功");
    }


    @ApiOperation(value = "获取已发送图片或视频的大小（如须要断点续传则和上传原图或（小）视频一起使用）")
    @PostMapping("/getSize")
    public Result<String> getSize(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取请求头中的数据，替换无法识别的符号
        String x_cameracode = request.getHeader("x-cameracode");
        String x_file_id = request.getHeader("x-file-id");
        String Content_Type = request.getHeader("Content-Type");

        System.out.println("*******"+"x_cameracode"+x_cameracode);
        System.out.println("*******"+"x_file_id"+x_file_id);
        System.out.println("*******"+"Content_Type"+Content_Type);

        MultipartFile file = tranMultipartFile(request.getInputStream(),Content_Type);
        //获取文件上传的名称
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            throw new ServerException("上传文件有误，请确认！");
        }

        String[] fileNameAttr = originalFilename.split("\\.");
        //获取文件的后缀
        String suffix = fileNameAttr[fileNameAttr.length - 1];
        String url = fdfsService.uploadFile(file,suffix);

        request.getInputStream();
        //表里面查已经上传的文件大小
        Integer already =0;
        //总续传大小
        response.setHeader("x-file-uploaded-size",already+file.getSize()+"");

        //todo 存表
        WiFiCaptureEntity wiFiCaptureEntity = new WiFiCaptureEntity();
        wiFiCaptureEntity.setCameraCode(x_cameracode);
        wiFiCaptureEntity.setPath(url);
        wiFiCaptureEntity.setFileId(x_file_id);
        wiFiCaptureService.insertWiFiCapture(wiFiCaptureEntity);
        return Result.write(200,"续传成功");
    }


    @ApiOperation(value = "获取原图/原视频")
    @PostMapping("/getOriginalPhoVid")
    public Result<String> downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取请求头中的数据，替换无法识别的符号
        String x_cameracode = request.getHeader("X-CameraCode");
        String x_file_id = request.getHeader("X-File-Id");
        String x_file_size = request.getHeader("X-File-Size");
        String x_is_hq = request.getHeader("X-Is-Hq");
        String Content_Type = request.getHeader("Content-Type");

        MultipartFile file = tranMultipartFile(request.getInputStream(),Content_Type);
        System.out.println(file.isEmpty());
        //获取文件上传的名称
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            throw new ServerException("上传文件有误，请确认！");
        }

        String[] fileNameAttr = originalFilename.split("\\.");
        //获取文件的后缀
        String suffix = fileNameAttr[fileNameAttr.length - 1];
        String url = fdfsService.uploadFile(file,suffix);

        request.getInputStream();
        //文件总大小
        response.setHeader("x-file-uploaded-size",file.getSize()+"");
        //续传几次累加上传的文件大小,续传需要累计，暂时不知道如何累计
        response.setHeader("x-file-session-uploaded-size",file.getSize()+"");

        //todo 存表
        WiFiCaptureEntity wiFiCaptureEntity = new WiFiCaptureEntity();
        wiFiCaptureEntity.setCameraCode(x_cameracode);
        wiFiCaptureEntity.setPath(url);
        wiFiCaptureEntity.setFileId(x_file_id);
        wiFiCaptureService.insertWiFiCapture(wiFiCaptureEntity);

        return Result.write(200,"上传原图或（小）视频成功");
    }


    @ApiOperation(value = "心跳获取")
    @PostMapping("/getHeartbeat")
    public Result<String> heartbeat(HttpServletRequest request ) throws Exception {

        HeartbeatDto dto = new HeartbeatDto();
        dto.setCameraCode(request.getParameter("cameraCode"));
        dto.setModel(request.getParameter("model"));
        dto.setCommTime(request.getParameter("commTime"));
        dto.setSignalStrength(request.getParameter("signalStrength"));
        dto.setBatteryLevel(request.getParameter("batteryLevel"));
        dto.setSdSpace(request.getParameter("sdSpace"));
        dto.setSdSpace(request.getParameter("sdFreeSpace "));

        dto.setLatitude(request.getParameter("latitude"));
        dto.setLongitude(request.getParameter("longitude"));
        dto.setTemperature(request.getParameter("temperature"));

        System.out.println("*******"+dto.toString());

        if(ObjectUtils.isEmpty(dto)){
            return Result.write(201,"心跳获取失败");
        }
        System.out.println("*******"+dto.toString());
        //todo 存表
//        //更新电量
//        UpdateWrapper<DeviceManager> wrapper = new UpdateWrapper<>();
//        wrapper.eq("device_sn",dto.getCameraCode());
//        wrapper.set("remaining_electricity",dto.getBatteryLevel()+"0%");
//        deviceManagerService.update(wrapper);
        return Result.write(200,"心跳获取成功");
    }

    @ApiOperation(value = "获取直播地址")
    @PostMapping("/getLiveBroadcast")
    public Result<String> GetLiveBroadcast(String url) throws Exception {
        if(ObjectUtils.isEmpty(url)){
            return Result.write(201,"播放地址获取失败");
        }
        System.out.println(url);
        //todo 发给前端
        return Result.write(200,"存储照片缩略图成功");
    }

    //**
    // 将输入流文件转换为MultipartFile,
    public MultipartFile tranMultipartFile(ServletInputStream inputStream,String name) throws IOException {
//       MultipartFile file = new MockMultipartFile("panda",name, MediaType.MULTIPART_FORM_DATA_VALUE, inputStream);
        if("image/jpeg".equals(name)){
            name ="jpg";
        }else if("video/mpeg4".equals(name)){
            name ="mp4";
        }
        MultipartFile file = new MultipartFileDto(name, inputStream);
        return file;
    }

    @ApiOperation("供熊猫基地查询资料使用")
    @GetMapping("/getData")
    public Result<List<WiFiCaptureEntity>> getData() {
        return Result.ok(wiFiCaptureService.getWiFiCaptureList());
    }

    @ApiOperation("熊猫APP查询数据资料")
    @PostMapping("/getListOfApp")
    public TableDataInfo getListOfApp(@RequestBody UmwWIFIDto umwWIFIDto) {
        startPage();
        return getDataTable(wiFiCaptureService.getWiFiCapApp(umwWIFIDto));
    }

    @ApiOperation("查询相机请求")
    @GetMapping("/getRequestInfo")
    public Result<List<WifiRequestInfo>> getRequestInfo() {
        return Result.ok(wiFiCaptureService.getRequestInfo());
    }

    public Date dateFormat(String oldDate) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = format.parse(oldDate);
        String date1 = format1.format(date);
        return format1.parse(date1);
    }

}
